<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>文档管理</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-icons.css') }}">
    <style>
        .hidden { display: none; }
        .upload-area {
            border: 2px dashed #ddd;
            padding: 2rem;
            text-align: center;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
        .back-btn {
            margin-right: 1rem;
        }
        .settings-panel {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 6px;
            margin-top: 1rem;
        }
        .hidden {
            display: none;
        }
        /* 美化按钮和下拉框 */
        .btn-outline-primary {
            border-width: 1.5px;
        }
        
        .form-select {
            border-width: 1.5px;
            border-color: #dee2e6;
        }
        
        .form-select:focus {
            border-color: #86b7fe;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
        
        /* 改善表格外观 */
        .table {
            border-radius: 0.5rem;
            overflow: hidden;
            box-shadow: 0 0 10px rgba(0,0,0,0.05);
        }
        
        .table thead th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
            font-weight: 500;
        }
        
        /* 改善上传区域样式 */
        .upload-area {
            border: 2px dashed #dee2e6;
            transition: all 0.3s ease;
        }
        
        .upload-area:hover {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
    </style>
    <script src="{{ url_for('static', filename='js/xlsx.full.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery-3.5.1.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/popper.min.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/all.min.css') }}">
</head>
<body>
    <div class="container mt-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div class="d-flex align-items-center">
                <a href="/" class="btn btn-outline-secondary back-btn">
                    <i class="bi bi-arrow-left"></i> 返回
                </a>
                <h2>文档管理</h2>
            </div>
            <!-- 修改按钮和下拉框的样式 -->
            <div class="d-flex align-items-center">
                <button id="createEmptyDoc" class="btn btn-outline-primary me-3">创建空文档</button>
                <select class="form-select" id="knowledgeSelect" style="width: 200px;">
                    <option value="">选择知识库</option>
                </select>
            </div>
        </div>

        <!-- 上传区域 -->
        <div class="upload-area hidden" id="dropZone">
            <div class="mb-3">
                <i class="bi bi-cloud-upload" style="font-size: 2rem;"></i>
            </div>
            <p class="mb-0">拖拽文件到此处或 <label for="file" class="text-primary" style="cursor: pointer;">点击上传</label></p>
            <input type="file" id="file" class="hidden" accept=".txt,.pdf,.doc,.docx,.csv,.xlsx,.xls">
            
            <!-- 添加设置表单 -->
            <form id="uploadForm" class="hidden mt-4">
                <div class="settings-panel">
                    <!-- 文本分割设置 - 仅用于非结构化文档 -->
                    <div id="textSplitPanel" class="hidden">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">切分策略</label>
                                    <select class="form-select" id="strategy" name="strategy">
                                        <option value="paragraph">段落分割</option>
                                        <option value="length">固定长度</option>
                                        <option value="sentence">句子分割</option>
                                        <option value="markdown">Markdown标题</option>
                                        <option value="sliding">滑动窗口分割</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">分块大小</label>
                                    <input type="number" class="form-control" id="chunk_size" name="chunk_size" value="1000">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">重叠大小</label>
                                    <input type="number" class="form-control" id="chunk_overlap" name="chunk_overlap" value="200">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 列映射配置面板 - 仅用于结构化数据 -->
                    <div id="columnMappingPanel" class="hidden">
                        <h5>数据列映射</h5>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">文档内容映射</label>
                                    <select class="form-select" id="documentColumns" multiple data-live-search="true">
                                    </select>
                                    <small class="text-muted">选择要包含在文档内容中的列</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">元数据映射</label>
                                    <select class="form-select" id="metadataColumns" multiple data-live-search="true">
                                    </select>
                                    <small class="text-muted">选择要包含在元数据中的列</small>
                                </div>
                            </div>
                            <!-- ✅ 新增 Embedding 映射 -->
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Embedding 映射</label>
                                    <select class="form-select" id="embeddingColumns" multiple data-live-search="true">
                                    </select>
                                    <small class="text-muted">选择用于生成向量的列</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="text-end mt-3">
                        <button type="submit" class="btn btn-primary">开始上传</button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 在upload-area div后添加进度条组件 -->
        <div id="uploadProgress" class="mt-3 hidden">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">处理进度</h5>
                    <div class="progress mb-3">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" 
                             role="progressbar" style="width: 0%" 
                             aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <div class="d-flex justify-content-between text-muted">
                        <small>已处理: <span id="processedItems">0</span>/<span id="totalItems">0</span></small>
                        <small>用时: <span id="elapsedTime">0秒</span></small>
                    </div>
                    <div id="uploadError" class="alert alert-danger mt-3 hidden"></div>
                </div>
            </div>
        </div>

        <!-- 文档列表 -->
        <table class="table">
            <thead>
                <tr>
                    <th>文件名</th>
                    <th>知识库</th>
                    <th>状态</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="documentsTable">
                <!-- 动态填充文档列表 -->
            </tbody>
        </table>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const knowledgeSelect = document.getElementById('knowledgeSelect');
            const dropZone = document.getElementById('dropZone');
            const fileInput = document.getElementById('file');
            const createEmptyDocBtn = document.getElementById('createEmptyDoc');

            // 获取URL参数中的knowledge_id
            const urlParams = new URLSearchParams(window.location.search);
            const preSelectedKnowledgeId = urlParams.get('knowledge_id');

            // 加载知识库列表
            fetch('/api/knowledges')
                .then(response => response.json())
                .then(data => {
                    const options = data.map(k => 
                        `<option value="${k.id}">${k.name}</option>`
                    ).join('');
                    knowledgeSelect.innerHTML += options;

                    // 如果有预选的knowledge_id，设置选中并触发change事件
                    if (preSelectedKnowledgeId) {
                        knowledgeSelect.value = preSelectedKnowledgeId;
                        dropZone.classList.remove('hidden');
                        loadDocuments(preSelectedKnowledgeId);
                    }
                })
                .catch(error => {
                    console.error('加载知识库列表失败:', error);
                });

            // 监听知识库选择
            knowledgeSelect.addEventListener('change', function() {
                dropZone.classList.toggle('hidden', !this.value);
                if (this.value) {
                    loadDocuments(this.value);
                }
            });

            // 创建空文档按钮点击事件
            createEmptyDocBtn.addEventListener('click', async () => {
                const knowledgeId = knowledgeSelect.value;
                if (!knowledgeId) {
                    alert('请先选择知识库');
                    return;
                }
                try {
                    const response = await fetch('/api/documents/create', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: new URLSearchParams({ knowledge_id: knowledgeId })
                    });
                    const result = await response.json();
                    if (response.ok) {
                        alert('空文档创建成功');
                        loadDocuments(knowledgeId);
                    } else {
                        alert(result.error || '创建失败');
                    }
                } catch (e) {
                    alert('创建失败: ' + e.message);
                }
            });

            // 加载文档列表
            function loadDocuments(knowledgeId) {
                if (!knowledgeId) return;
                
                fetch(`/api/documents?knowledge_id=${knowledgeId}`)
                    .then(response => response.json())
                    .then(data => {
                        // 确保data是数组
                        const documents = Array.isArray(data) ? data : [];
                        
                        if (documents.length === 0) {
                            document.getElementById('documentsTable').innerHTML = `
                                <tr>
                                    <td colspan="5" class="text-center text-muted">
                                        <i class="bi bi-info-circle me-2"></i>暂无文档
                                    </td>
                                </tr>`;
                            return;
                        }

                        const html = documents.map(doc => `
                            <tr>
                                <td>${doc.filename}</td>
                                <td>${doc.knowledge_name}</td>
                                <td>
                                    <span class="badge ${doc.status === 'completed' ? 'bg-success' : 'bg-warning'}">
                                        ${doc.status === 'completed' ? '处理完成' : '处理中'}
                                    </span>
                                </td>
                                <td>${new Date(doc.created_at).toLocaleString()}</td>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group" aria-label="操作按钮">
                                        <a href="/api/documents/download/${doc.id}" class="btn btn-outline-secondary" title="下载文档">
                                            <i class="bi bi-cloud-download"></i>
                                        </a>
                                        <button onclick="deleteDocument('${doc.id}')" class="btn btn-outline-secondary" title="删除文档">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                        <a href="/segments?document_id=${doc.id}&document_name=${encodeURIComponent(doc.filename)}&knowledge_id=${knowledgeId}" class="btn btn-outline-secondary" title="查看分片">
                                            <i class="bi bi-bar-chart"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        `).join('');
                        document.getElementById('documentsTable').innerHTML = html;
                    })
                    .catch(error => {
                        console.error('加载文档列表失败:', error);
                        document.getElementById('documentsTable').innerHTML = `
                            <tr>
                                <td colspan="5" class="text-center text-danger">
                                    <i class="bi bi-exclamation-triangle me-2"></i>加载失败，请刷新重试
                                </td>
                            </tr>`;
                    });
            }

            // 文件上传处理
            document.getElementById('file').addEventListener('change', async function(e) {
                const file = this.files[0];
                if (!file) return;

                const uploadForm = document.getElementById('uploadForm');
                const textSplitPanel = document.getElementById('textSplitPanel');
                const columnMappingPanel = document.getElementById('columnMappingPanel');
                
                // 显示上传表单
                uploadForm.classList.remove('hidden');

                // 判断文件类型
                const isStructured = /\.(csv|xlsx?)$/i.test(file.name);
                
                if (isStructured) {
                    // 显示列映射面板，隐藏文本分割面板
                    columnMappingPanel.classList.remove('hidden');
                    textSplitPanel.classList.add('hidden');
                    
                    // 读取文件获取列名
                    try {
                        const columns = await getFileColumns(file);
                        populateColumnSelects(columns);
                    } catch (error) {
                        console.error('读取文件列失败:', error);
                        alert('读取文件结构失败，请检查文件格式');
                    }
                } else {
                    // 显示文本分割面板，隐藏列映射面板
                    textSplitPanel.classList.remove('hidden');
                    columnMappingPanel.classList.add('hidden');
                }
            });

            // 读取文件列名
            async function getFileColumns(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        try {
                            if (file.name.endsWith('.csv')) {
                                // 读取CSV文件前几行来获取列名
                                const text = e.target.result;
                                const firstLine = text.split('\n')[0];
                                const columns = firstLine.split(',').map(col => col.trim().replace(/"/g, ''));
                                resolve(columns);
                            } else {
                                // 读取Excel文件列名
                                const data = new Uint8Array(e.target.result);
                                const workbook = XLSX.read(data, {type: 'array'});
                                const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                                const columns = [];
                                const range = XLSX.utils.decode_range(worksheet['!ref']);
                                
                                for (let col = range.s.c; col <= range.e.c; col++) {
                                    const cell = worksheet[XLSX.utils.encode_cell({r: 0, c: col})];
                                    if (cell && cell.v) {
                                        columns.push(cell.v.toString());
                                    }
                                }
                                resolve(columns);
                            }
                        } catch (error) {
                            reject(error);
                        }
                    };
                    
                    reader.onerror = () => reject(reader.error);
                    
                    if (file.name.endsWith('.csv')) {
                        reader.readAsText(file);
                    } else {
                        reader.readAsArrayBuffer(file);
                    }
                });
            }

            // 填充列选择下拉框
            function populateColumnSelects(columns) {
                const documentColumns = document.getElementById('documentColumns');
                const metadataColumns = document.getElementById('metadataColumns');
                const embeddingColumns = document.getElementById('embeddingColumns'); 
                
                const options = columns.map(col => 
                    `<option value="${col}">${col}</option>`
                ).join('');
                
                documentColumns.innerHTML = options;
                metadataColumns.innerHTML = options;
                embeddingColumns.innerHTML = options;
            }

            // 处理表单提交
            document.getElementById('uploadForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const knowledgeId = knowledgeSelect.value;
                if (!knowledgeId) {
                    alert('请先选择知识库');
                    return;
                }

                const file = fileInput.files[0];
                if (!file) {
                    alert('请选择文件');
                    return;
                }

                const formData = new FormData();
                formData.append('file', file);
                formData.append('knowledge_id', knowledgeId);
                
                // 添加分割设置
                formData.append('strategy', document.getElementById('strategy').value);
                formData.append('chunk_size', document.getElementById('chunk_size').value);
                formData.append('chunk_overlap', document.getElementById('chunk_overlap').value);
                
                // 如果是结构化数据，添加列映射
                if (file.name.toLowerCase().endsWith('.csv') || 
                    file.name.toLowerCase().endsWith('.xlsx') || 
                    file.name.toLowerCase().endsWith('.xls')) {
                    const documentColumns = Array.from(document.getElementById('documentColumns').selectedOptions)
                                            .map(option => option.value);
                    const metadataColumns = Array.from(document.getElementById('metadataColumns').selectedOptions)
                                            .map(option => option.value);
                    const embeddingColumns = Array.from(document.getElementById('embeddingColumns').selectedOptions)
                                            .map(option => option.value);
                    
                    formData.append('document_columns', JSON.stringify(documentColumns));
                    formData.append('metadata_columns', JSON.stringify(metadataColumns));
                    formData.append('embedding_columns', JSON.stringify(embeddingColumns));
                }

                try {
                    // 显示进度条
                    const progressDiv = document.getElementById('uploadProgress');
                    const progressBar = progressDiv.querySelector('.progress-bar');
                    const processedItems = document.getElementById('processedItems');
                    const totalItems = document.getElementById('totalItems');
                    const elapsedTime = document.getElementById('elapsedTime');
                    const errorDiv = document.getElementById('uploadError');
                    
                    progressDiv.classList.remove('hidden');
                    errorDiv.classList.add('hidden');
                    
                    // 上传文件
                    const response = await fetch('/api/documents/upload', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(result.error || '上传失败');
                    }
                    
                    // 开始轮询进度
                    const startTime = Date.now();
                    const taskId = result.task_id;
                    
                    const pollProgress = async () => {
                        try {
                            const statusResponse = await fetch(`/api/tasks/${taskId}`);
                            const statusResult = await statusResponse.json();
                            
                            // 更新进度条
                            const progress = statusResult.progress;
                            progressBar.style.width = `${progress}%`;
                            progressBar.setAttribute('aria-valuenow', progress);
                            
                            // 更新处理信息
                            processedItems.textContent = statusResult.processed_items;
                            totalItems.textContent = statusResult.total_items;
                            
                            // 更新用时
                            const elapsed = Math.floor((Date.now() - startTime) / 1000);
                            elapsedTime.textContent = `${elapsed}秒`;
                            
                            // 根据状态决定是否继续轮询
                            if (statusResult.status === 'completed') {
                                // 重置表单
                                document.getElementById('uploadForm').reset();
                                document.getElementById('uploadForm').classList.add('hidden');
                                fileInput.value = '';
                                
                                // 延迟隐藏进度条
                                setTimeout(() => {
                                    progressDiv.classList.add('hidden');
                                }, 2000);
                                
                                // 重新加载文档列表
                                loadDocuments(knowledgeId);
                                return;
                            } else if (statusResult.status === 'failed') {
                                errorDiv.textContent = statusResult.error_message;
                                errorDiv.classList.remove('hidden');
                                return;
                            }
                            
                            // 继续轮询
                            setTimeout(pollProgress, 1000);
                        } catch (error) {
                            console.error('获取进度失败:', error);
                            errorDiv.textContent = '获取进度失败: ' + error.message;
                            errorDiv.classList.remove('hidden');
                        }
                    };
                    
                    // 开始轮询
                    pollProgress();
                    
                } catch (error) {
                    alert('上传失败: ' + error.message);
                }
            });

            // 删除文档
            function deleteDocument(docId) {
                if (confirm('确定要删除此文档吗？')) {
                    fetch(`/api/documents/${docId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.error) {
                            alert(result.error);
                        } else {
                            const knowledgeId = document.getElementById('knowledgeSelect').value;
                            loadDocuments(knowledgeId);
                        }
                    });
                }
            }

            // 将 deleteDocument 设置为全局函数
            window.deleteDocument = deleteDocument;
        });

        

        // // 修改查看分片按钮的点击事件
        // $('#records-table').on('click', '.view-segments', function() {
        //     const documentId = $(this).data('id');
        //     const documentName = $(this).data('name'); // 添加文件名
        //     //const knowledgeId = $(this).data('knowledge_id'); // 新增知识库ID
        //     //window.location.href = `/segments?document_id=${documentId}&document_name=${encodeURIComponent(documentName)}&knowledge_id=${knowledgeId}`;
        //     window.location.href = `/segments?document_id=${documentId}&document_name=${encodeURIComponent(documentName)}`;
        // });
    </script>
</body>
</html>